<template>
  <div class='u-selectAttr'>
    <el-form :inline="true">

      <!-- 输入类型 -->
      <el-form-item label='输入内容' v-if='selectStatusValueType === "1"'>
        <el-input v-model.trim='classContent' type='text' @change="addSku(0)"/>
      </el-form-item>

      <!--选择分类-->
      <el-form-item v-else>
        <el-select  multiple v-model="selectedCourseClassArray" @change='selectedCourseClass'>
          <el-option v-for='(v) in courseClasslist' :disabled="v.disabled" :key='v.id' :value="v.id" :label="v.name">
          </el-option>
        </el-select>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
  /**
   * 选择预定义分类模块
   * 点击选择属性按钮，显示当前模块
   * 注意！现在的功能，只有选择添加，编辑貌似被去掉了，暂不维护编辑功能
   * 只要选中了属性，就可以添加一个 sku
   */
  import {setAttrData, createSkuById, formatDetailDataToAttrList} from '@/util/formatAttr'

  export default {

    name: 'su-selectAttrList3',

    /**
     * @param {String} openType 打开的方式，add or edit
     * @param {Number} selectIndex 编辑时，点击的位置
     * @param {Array<object>} skuList sku 数组
     * @param {String} aType 获取属性的类型（商品、客户、订单等）
     */
    props: ['openType', 'selectIndex', 'skuList', 'selectStatus', 'aType', 'attrs', 'def', 'list', 'isSkuIndex'],

    data() {
      return {
        ifRequesting: false,
        dialogVisible: false,
        // 属性数组
        courseFeatureList: [],
        courseFeatureList_tmp: [],
        // 一级分类
        courseClasslist: [],
        // 二级分类
        courseClasslist2: [],
        // 选中的一级分类
        selectedCourseClassArray: [],
        // 选中的属性
//        selectStatus: '',
        // 选中的属性类型
        selectStatusValueType: '',
        // 输入类型的分类内容
        classContent: '',
        attrList: []
      }
    },

    mounted() {
      // this.getAttributes()
      this.getAllAttrAndClass()
      this.selectedAttr(this.selectStatus)
    },

    methods: {
      clearForm() {
        this.courseClasslist = []
        this.selectedCourseClassArray = []
        this.courseClasslist2 = []
        this.selectStatus = ''
        this.selectStatusValueType = ''
        this.classContent = ''
      },

      async getAllAttrAndClass() {
        let list = this.list
        if (this.attrs) {
          const attr = formatDetailDataToAttrList(this.attrs) // 转换格式
          // def：自定义、预定义、其他
          attr.forEach((item) => {
            if (this.def === item.is_self_def && parseInt(item.is_require) !== 1) {
              list.push(item)
            }

            if (item.id === this.selectStatus) {
              this.selectedCourseClassArray = item.selects
            }
          })
        }
        this.formatAttrAndClassData(list)
      },

      /**
       * 组织 属性 -> 分类 -> 子级分类 的数据结构
       * 分类数据结构（一级） -> classes
       */
      formatAttrAndClassData(data) {
        data.forEach(v => {
          this.attrList.push(setAttrData(v))
        })
      },

      /**
       * 选择属性触发的回调
       * @param {String} 选中的属性 id
       */
      selectedAttr(id) {
        if (!id && id !== 0) {
          this.addSku(0)
          return
        }
        // 根据 id 获取选中的属性
        const obj = this.attrList.filter(v => v.id === id)[0]
        this.selectStatusValueType = obj.value_type
        // 输入类型就结束
        if (this.selectStatusValueType === '1') {
          this.addSku(0)
          return false
        }
        // 切换 class
        this.courseClasslist = obj.classes
        this.addSku(0)
      },

      /**
       * 选择一级分类触发的回调
       * @param {Array} classesId 选中的 classes id 位置数组
       */
      selectedCourseClass(classesId) {
        if (classesId.length === 0) {
          this.addSku(0)
          return false
        }
        this.courseClasslist.forEach((v) => {
          const isHaveSame = classesId.some(id => {
            if (v.id === id) {
              v.isShowClass = true
              this.addSku(0)
              return true
            }
          })
          if (!isHaveSame) {
            // 清空之前选中的
            v.selects = []
            v.isShowClass = false
          }
        })
        this.addSku(0)
      },

      /**
       * 添加新的 sku
       * 根据 List 文件定义好的 sku 数据结构生成对象
       */
      addSku(type) {
//        const selectIndex = this.selectIndex
        this.$emit('getSku',
          createSkuById(type, this.attrList, this.selectStatus, this.selectStatusValueType, this.classContent), this.isSkuIndex)
      },

      async courseGetClasses() {
        const arr = []
        this.courseClasslist2.every(async v => {
          arr.push(new Promise(async resolve => {
            const data = await this.getClasses2(v.id, 'edit')
            v.list = data
            resolve()
          }))
        })
        return Promise.all(arr)
      },

      async editSku(obj) {
        this.selectStatus = obj.feature.value
        this.courseFeatureList = JSON.parse(JSON.stringify(this.courseFeatureList_tmp.map(v => v)))
        this.selectStatusValueType = this.courseFeatureList_tmp.filter(v => v.value === obj.feature.value)[0].value_type
        // 生成一级分类
        this.courseClasslist = []
        this.selectedCourseClassArray = []
        if (obj.feature.value_type === '1') {
          console.log(obj)
          this.classContent = obj.classes[0].name
          return
        }
        await this.getClasses(obj.feature.value, 'edit')
        this.courseClasslist.forEach((v, i) => {
          obj.classes.forEach(v2 => {
            if (v.id === v2.id) {
              this.selectedCourseClassArray.push(i)
            }
          })
        })
        this.courseClasslist2 = []
        // 生成二级分类
        console.log(obj)
        this.selectedCourseClassArray.forEach(v => {
          this.courseClasslist2.push({
            id: this.courseClasslist[v].id,
            name: this.courseClasslist[v].name,
            list: [],
            selects: []
          })
        })
        // 添加已选中的和获取列表
        await this.courseGetClasses()
        obj.classes2.forEach((v) => {
          this.courseClasslist2.forEach(async (item, i) => {
            if (v.parentId === item.id) {
              console.log(this.courseClasslist2[i].list)
              item.list.forEach((child, i) => {
                console.log(child.id, v.id)
                if (child.id === v.id) {
                  item.selects.push(i)
                }
              })
            }
          })
        })
        console.log(this.courseClasslist2)
      },

      // 除去选中的属性
      deleteCheckedAttr() {
        this.courseFeatureList = JSON.parse(JSON.stringify(this.courseFeatureList_tmp.map(v => v)))
        this.skuList.forEach(sku => {
          this.courseFeatureList.some((v, i) => {
            if (v.value === sku.feature.value) {
              this.courseFeatureList.splice(i, 1)
              return true
            }
            return false
          })
        })
      },

      // 将已选的分类，添加 disabled
      addDisabledFromCheckedClass(data, type, edit) {
        console.log(edit, this.selectIndex)
        return data
      },
      removeTag(value) {
        this.$emit('removeTag', value)
      }
    }
  }
</script>

<style lang='less' scoped>
  .u-selectAttr {
    .el-form-item {
      /*padding-bottom: 20px;*/
      /*display: flex;*/
    }
    .btnWrap {
      display: flex;
      justify-content: flex-end;
    }
    &-selectWrap {
      overflow: hidden;
      .item {
        display: flex;
        /*padding-bottom: 10px;*/
        p {
          /*padding-right: 20px;*/
        }
      }
    }
  }
</style>
